﻿using BigMonitoringWarningApi.Model.ApiResult;
using BigMonitoringWarningApi.Tool.Extension;
using GYCTOAManagementSystemNewApi.Model;
using GYCTOAManagementSystemNewApi.Model.DTO.AccountManagement;
using GYCTOAManagementSystemNewApi.Model.Entity;
using GYCTOAManagementSystemNewApi.Model.Enum;
using GYCTOAManagementSystemNewApi.Model.Tool;
using GYCTOAManagementSystemNewApi.Model.ViewModel;
using GYCTOAManagementSystemNewApi.Public;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Transactions;

namespace GYCTOAManagementSystemNewApi.Controllers
{
    /// <summary>
    /// 账号管理
    /// </summary>
    public class AccountManagementController : BaseController
    {
        //private readonly ILogger<CustomerController> _logger;
        DBContext _db;
        PublicTool _publictool;
        public AccountManagementController(/*ILogger<CustomerController> logger, */DBContext db)
        {
           // _logger = logger;
            _db = db;
            _publictool = new PublicTool(_db);
        }
        #region 账号管理
        /// <summary>
        /// 数据查询
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiPageResult<List<AccountManagement>>> GetAccountManagementDetail([FromBody] dynamic formData)
        {
            try
            {
                JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
                int offset = Convert.ToInt32(j_token["currentPage"]);
                int limit = Convert.ToInt32(j_token["pagesize"]);
                var Key = j_token["key"].ToString();
                var query = _db.AccountManagement.Where(x => !x.Delete);
                if (!string.IsNullOrWhiteSpace(Key))
                {
                    query = query.Where(x => x.AccountName.Contains(Key)
                    || x.Theurl.Contains(Key)
                    || x.Account.Contains(Key)
                    );
                }
                var total = query.Count();
                var rows =await query.Skip((offset - 1) * limit).Take(limit).ToListAsync();
                foreach (var item in rows)
                {
                    item.PassWord = "";
                }
                return ApiPageResult.True(rows, offset, limit, total);
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        /// <summary>
        /// 判断操作权限
        /// </summary>
        /// <param name="id">持有人Id</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> IsPowerAccountManagement(int[] arrDel)
        {
            {
                if (arrDel.Distinct().Count() > 1)
                {
                    return ApiResult.False("请选择同一归属人账号操作");
                }
                var UserId = HttpContext.User.Claims.FirstOrDefault().Value.ToInt();
                if (arrDel[0].Equals(UserId))
                {
                    return ApiResult.True();
                }
                return ApiResult.False("请使用归属人账号操作");
            }
        }


        /// <summary>
        /// 根据Id 查询账号信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> AccountManagementByCheck([FromBody] dynamic formData)
        {
            AccountManagementCheckDto accountManagement = JsonConvert.DeserializeObject<AccountManagementCheckDto>(formData.ToString());
            var UserByid = _db.Users.Find(accountManagement.UserId.ToInt());
            if (UserByid!=null)
            {
                if (UserByid.Password.Equals(accountManagement.Password))
                {
                    return ApiResult.True(_db.AccountManagement.Find(accountManagement.AccountId));
                }
              return ApiResult.False("账户密码不正确");
            }
            return ApiResult.False("当前用户不存在");
        } 

        /// <summary>
        /// 根据Id 查询账号信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> AccountManagementById([FromBody] dynamic formData)
        {
            JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
            int id = j_token["Id"].ToInt();
            return ApiResult.True(_db.AccountManagement.Find(id));
        }
         

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="arrDel"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> DeleteAccountManagementContent(int[] arrDel)
        {
            var UserId= HttpContext.User.Claims.FirstOrDefault().Value;
            
                using (System.Transactions.TransactionScope ts = new TransactionScope())
                {
                    foreach (var t in arrDel)
                    {
                        var obj = _db.AccountManagement.Find(t);
                        if (obj == null)
                        {
                            return ApiResult.False("信息提交失败");
                        }
                        obj.Delete = true;
                        obj.OperatDate = DateTime.Now;
                        obj.OperatId = Convert.ToInt32(UserId);
                    }
                    ts.Complete();
                }
            if (await _db.SaveChangesAsync() > 0)
            {
                return ApiResult.True();
            }
            return ApiResult.False("信息提交失败");
        }
        /// <summary>
        /// 添加文档
        /// </summary>
        /// <param name="AccountManagement"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult>  AddAccountManagementContent([FromBody] dynamic formData)
        {
            AccountManagement accountManagement = JsonConvert.DeserializeObject<AccountManagement>(formData.ToString());
            var UserId = HttpContext.User.Claims.FirstOrDefault().Value;
            accountManagement.OperatDate = DateTime.Now;
            accountManagement.OperatId = UserId.ToInt();
            if (_db.AccountManagement.Where(x => x.AccountName.Equals(accountManagement.AccountName) && !x.Delete).Count() > 0)
            {
                return ApiResult.False("已存在相同的名称请删除后再次添加");
            }
            _db.AccountManagement.Add(accountManagement);
            if (await _db.SaveChangesAsync() > 0)
            {
                return ApiResult.True();
            }
            return ApiResult.False("信息提交失败");
        }
        /// <summary>
        /// 修改文档
        /// </summary>
        /// <param name="AccountManagement"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> UpdateAccountManagementContent([FromBody] dynamic formData)
        {
            AccountManagement accountManagement = JsonConvert.DeserializeObject<AccountManagement>(formData.ToString());
            var UserId = HttpContext.User.Claims.FirstOrDefault().Value;
            accountManagement.OperatDate = DateTime.Now;
            accountManagement.OperatId = UserId.ToInt();
            _db.AccountManagement.Update(accountManagement);
            if (await _db.SaveChangesAsync()>0)
            {
                return ApiResult.True();
            }
            return ApiResult.False("文档修改失败");
        }
        #endregion
    }
}
